<template>
  <table width="500" border>
    <thead>
      <th>名称</th>
      <th>数量</th>
      <th>价格</th>
      <th></th>
    </thead>
    <tbody>
      <tr v-for="(item, index) in data" :key="item.name">
        <td>{{ item.name }}</td>
        <td><button @click="change(item, false)">-</button> {{ item.num }} <button @click="change(item, true)">+</button></td>
        <td>{{ item.price * item.num }}</td>
        <td><button @click="del(index)">删除</button></td>
      </tr>
      <tr>
        <td colspan="3"></td>
        <td>总价: {{ total }}</td>
      </tr>
    </tbody>
  </table>
</template>

<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'

type Shop = {
  name: string,
  num: number,
  price: number,
}

const data = reactive<Shop[]>([
  { name: '苹果', num: 1, price: 20 },
  { name: '香蕉', num: 1, price: 26 },
  { name: '橘子', num: 1, price: 12 },
])
const change = (item: Shop, flag: boolean) => {
  if (!flag && item.num > 1) {
    item.num--
    return
  }
  item.num++
}

const total = computed(() => {
  return data.reduce((prev, next) => {
    return prev + next.price * next.num
  }, 0)
})
const del = (index: number) => {
  data.splice(index, 1)
}

</script>

<style lang='scss' scoped>
table {
  border-collapse: collapse;
}
</style>